<template>
  <div>
    <!-- <el-dialog :title="'给'+billingData.customerName+'开单'" :visible.sync="modalShow" width="60%" :before-close="modalClose" center> -->
    <Dialog title="增加套餐" :visible.sync="modalShow" :width="60" :loading="loading" :before-close="modalClose" class="wide-popup" @confirm="handlerSubmit" @close="modalClose">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称：" prop="dataName">
              <el-input v-model="ruleForm.dataName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类：" prop="classify">
              <el-cascader
                v-model="ruleForm.classify"
                :options="projectList"
                :props="{value: 'id',
                         label: 'dataName',
                         children: 'children',
                         checkStrictly: true,
                }"
                style="width: 100%"
                class="el-select-y"
                @change="classificationSelection"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="套餐价格：" prop="price">
              <el-input v-model="ruleForm.price" disabled />
              根据套餐物品自动计算
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="允许折扣下限：" prop="discount">
              <el-input v-model="ruleForm.discount" style="width:327px" />%
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="状态：" prop="status">
              <el-radio-group v-model="ruleForm.status">
                <el-radio label="上架" />
                <el-radio label="下架" />
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <p class="font-weight">挑选</p>
        <el-container class="choose">
          <el-aside width="195x">
            <LeftClassification :tabs-text="tabsText" @classificationClist="getClassificationId" @tabsVales="handleTabs" />
          </el-aside>
          <el-main>
            <div v-show="tabsBool===1">
              <el-input v-model="val" placeholder="请输入名称和拼音码" style="width:30%;margin-bottom: 10px" @input="valChange" />
              <el-table v-if="tabsBool===1" ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" @select="handlechange" @select-all="allHandleChange">
                <el-table-column label="名称" prop="name" align="center" />
                <el-table-column prop="productAttributes" label="属性" align="center" show-overflow-tooltip />
                <el-table-column prop="specifications" label="规格" align="center" show-overflow-tooltip />
                <el-table-column prop="unit" label="单位" align="center" show-overflow-tooltip />
                <el-table-column prop="usageTimes" label="使用次数" align="center" show-overflow-tooltip />
                <el-table-column prop="price" label="售价" align="center" show-overflow-tooltip />
                <el-table-column
                  type="selection"
                  label="操作"
                  align="center"
                  width="55"
                />
              </el-table>
            </div>
            <div v-show="tabsBool===2">
              <el-input v-model="val" placeholder="请输入名称和拼音码" style="width:30%;margin-bottom: 10px" @input="valChange" />
              <el-table v-if="tabsBool===2" ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" @select="handlechange" @select-all="allHandleChange">
                <el-table-column label="名称" prop="name" align="center" />
                <el-table-column prop="searchCode" label="拼音码" align="center" />
                <el-table-column prop="specifications" label="规格" align="center" show-overflow-tooltip />
                <el-table-column prop="unit" label="单位" align="center" show-overflow-tooltip />
                <el-table-column prop="price" label="售价" align="center" show-overflow-tooltip />
                <el-table-column
                  type="selection"
                  label="操作"
                  align="center"
                  width="55"
                />
              </el-table>
            </div>
          </el-main>
        </el-container>
        <div>
          <ul v-if="selectTables.length>0">
            <li class="detailed font-weight">
              商品清单：
            </li>
            <li v-for="(items,i) of selectTables" :key="i">
              <el-row style="width:5%">
                <el-col>
                  <el-checkbox v-model="items.checkeds" />
                </el-col>
                <el-col>
                  <el-button type="text" @click="handleDelete(items)"><i class="el-icon-close" /></el-button>
                </el-col>
              </el-row>
              <el-row style="width:100%">
                <el-row type="flex">
                  <el-col :span="19" class="product">
                    <el-button class="bg" type="text">{{ items.contentType }}</el-button><span style="margin-left:10px;line-height:30px">{{ items.name }}</span>
                    <p style="margin:0px 10px;">{{ items.printName }}</p>
                  </el-col>
                  <el-col :span="3">
                    <el-input-number v-model="items.contentCount" type="number" :min="1" :max="10" label="描述文字" />
                  </el-col>
                </el-row>
                <el-row class="grey" type="flex">
                  <el-col :span="19">
                    <span>规格：{{ items.specifications }}</span>
                    <span>单位：{{ items.unit }}</span>
                    <span v-if="items.contentType === '项目'">使用次数：{{ items.usageTimes }}</span>
                  </el-col>
                </el-row>
                <el-row type="flex" class="price">
                  <el-col :span="6">
                    售价：￥{{ items.price }}
                  </el-col>
                  <el-col :span="5" :offset="8">
                    套餐折扣
                    <el-input v-model="items.discountRate" style="width:40%" @blur="discountChange(items)" />
                    %
                  </el-col>
                  <el-col :span="5">
                    套餐金额：
                    <el-input v-model="items.discountPrice" style="width:40%" />
                  </el-col>
                </el-row>
              </el-row>
            </li>
          </ul>
          <el-row v-if="selectTables.length>0">
            <el-col :offset="20" :span="6">总额：￥{{ allPrice }}</el-col>
            <el-col :offset="20" :span="6">优惠：-￥{{ discountPrice }}</el-col>
            <el-col :offset="20" :span="6">合计：<span class="spns">￥{{ setMealPrice }}</span></el-col>
          </el-row>
        </div>
        <!-- <el-form-item>
          <el-row type="flex">
            <el-col :span="3" :offset="8">
              <el-button plain type="primary" @click="handlerSubmit('ruleForm')">提交</el-button>
            </el-col>
            <el-col :span="3" :offset="2">
              <el-button plain @click="modalClose">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item> -->
      </el-form>
    </Dialog>
  </div>

</template>

<script>
// import { mapMutations } from 'vuex';
import Dialog from '@/components/Dialog';
import LeftClassification from "@/components/leftClassification";
export default {
  name: "Index",
  components: {
    Dialog,
    LeftClassification,
  },
  props: {
    billingData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      tabsText: [
        { label: '项目', name: 'product' },
        { label: '物品', name: 'drugs' },
      ],
      tabsBool: 1,
      searchParams: {
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      },
      modalShow: false,
      loading: false,
      ruleForm: {},
      rules: {
        dataName: [// 主要需求
          { required: true, message: '请输入套餐名称', trigger: 'blur' },
        ],
        classify: [
          { required: true, message: '请选择分类', trigger: 'change' },
        ],
        price: [
          { required: true, message: '请选择套餐物品', trigger: 'blur' },
        ],
      },
      tableData: [],
      selectTables: [],
      projectList: [],
      allPrice: 0,
      discountPrice: 0,
      setMealPrice: 0,
      val: "",
      tableDataList: [],
    };
  },
  computed: {
    userInfo() {
      return this.$store.getters.currentUserInfo;
    },
  },
  watch: {
    billingData: {
      handler(newVal) {
        this.ruleForm = JSON.parse(JSON.stringify(newVal));
        this.selectTables = [];
        this.checkedIdList = [];
        const list = [];
        if (this.ruleForm.comboDetailDtoList && this.ruleForm.comboDetailDtoList.length > 0) {
          this.ruleForm.comboDetailDtoList.forEach(item => {
            if (item.type === "项目类") {
              Object.assign(item, item.productDto);
            } else {
              item.specifications = item.spec;
              Object.assign(item, item.materialMedicineDto);
            }
            this.$set(item, "contentType", item.type.split("类")[0]);
            this.$set(item, "contentCount", item.count);
            this.$set(item, "price", item.comboPrice);
            this.$set(item, "discountPrice", item.comboPrice);
            this.$set(item, "checkeds", true);
            this.$set(item, "discountRate", item.discount);
            list.push(item);
            this.checkedIdList.push(item.id);
          });
        }
        this.selectTables = list;
      },
      deep: true,
      immediate: true,
    },
    selectTables: {
      handler(val) {
        if (val && val.length > 0) {
          let allPrice = 0;
          let discountPrice = 0;
          let setMealPrice = 0;
          val.forEach(item => {
            if (item.checkeds) {
              allPrice += Math.floor((Number(item.contentCount) * Number(item.price)).toFixed(2) * 100) / 100;
              setMealPrice += Math.floor((Number(item.contentCount) * Number(item.discountPrice)).toFixed(2) * 100) / 100;
            }
          });
          setMealPrice = Math.floor(setMealPrice.toFixed(2) * 100) / 100;
          discountPrice = (allPrice - setMealPrice).toFixed(2) * 100 / 100;
          this.allPrice = allPrice;
          this.discountPrice = discountPrice;
          this.setMealPrice = setMealPrice;
          this.ruleForm.price = setMealPrice;
          this.ruleForm.originalPrice = allPrice;
          this.ruleForm.discountPrice = discountPrice;
          // this.$refs.ruleForm.clearValidate();
        } else {
          this.ruleForm.price = 0;
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    this.getProjectClass();
    if (!this.ruleForm.status) {
      this.$set(this.ruleForm, 'status', "上架");
    }
  },
  methods: {
    async getProjectClass() {
      const res = await this.$api['data/goods/treeList']({ dataType: "项目类" });
      if (res.code !== 200) return this.$message.error('查询项目列表失败！');
      this.projectList = res.data;
    },
    async handleDelete(items) {
      const confirmResult = await this.$confirm('请确认是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err);
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除');
      } else {
        this.$nextTick(function() {
          this.selectTables.forEach((item, i) => {
            if (item.id === items.id) {
              this.selectTables.splice(i, 1);
            }
          });
          this.tableData.forEach(row => {
            if (items.id === row.id) {
              this.$refs.multipleTable.toggleRowSelection(row, false);
            }
          });
          return this.$message.success('已删除成功');
        });
      }
    },
    handleTabs(val) {
      if (val === 'product') {
        this.tabsBool = 1;
      } else {
        this.tabsBool = 2;
      }
      this.val = "";
      this.tableData = [];
    },
    async getClassificationId(val) {
      // 查询提交的产品分类id
      this.searchParams.productClassificationId = val.list.join(",");
      if (this.tabsBool === 1) {
        const res = await this.$api['doctor/consulting/productList']({ query: this.searchParams });
        if (res.code !== 200) return this.$message.error('查询项目列表失败！');
        this.tableDataList = res.data;
        this.tableData = JSON.parse(JSON.stringify(this.tableDataList));
        this.tableData.forEach(item => {
          this.$set(item, 'contentCount', 1);
          this.$set(item, 'contentType', '项目');
          this.$set(item, 'discountRate', '100');
          this.$set(item, 'discountPrice', item.price);
          this.$set(item, 'attendingDoctor', '');
        });
      } else if (this.tabsBool === 2) {
        const res = await this.$api['data/drugs/drugsList']({ query: { ...this.searchParams, inventory: "进货" }});
        if (res.code !== 200) return this.$message.error('查寻物品列表失败！');
        this.tableDataList = res.data;
        this.tableData = JSON.parse(JSON.stringify(this.tableDataList));
        this.tableData.forEach(item => {
          this.$set(item, 'contentCount', 1);
          this.$set(item, 'contentType', '物品');
          this.$set(item, 'discountRate', '100');
          this.$set(item, 'discountPrice', item.sellPrice);
          this.$set(item, 'price', item.sellPrice);
          this.$set(item, 'attendingDoctor', '');
        });
      }
      if (this.selectTables.length > 0) {
        this.$nextTick(function() {
          this.tableData.forEach(item => {
            this.selectTables.forEach(json => {
              if (item.id === json.id) {
                this.$refs.multipleTable.toggleRowSelection(item, true);
              }
            });
          });
        });
      }
    },
    init() {
      this.modalShow = true;
      this.$nextTick(() => {
        this.$refs.multipleTable.clearSelection();
        this.$refs.ruleForm.clearValidate();
      });
    },
    handlerSubmit() {
      this.$refs['ruleForm'].validate(async(valid) => {
        if (valid) {
          this.ruleForm.creator = this.$store.getters.currentUserInfo.name;
          const pinyinCode = this.$pinyin(this.ruleForm.dataName, { style: this.$pinyin.STYLE_NORMAL, heteronym: true });
          this.ruleForm.pinyinCode = "";
          pinyinCode.forEach(item => {
            this.ruleForm.pinyinCode += item;
          });
          this.ruleForm.comboDetailEntities = [];
          if (this.selectTables.length === 0) {
            this.$message.error('请选择项目');
            return;
          }
          this.selectTables.forEach(item => {
            if (item.checkeds) {
              const json = {
                comboPrice: item.discountPrice,
                count: item.contentCount,
                discount: item.discountRate,
                type: item.contentType + "类",
                untitled: item.id,
              };
              this.ruleForm.comboDetailEntities.push(json);
            }
          });
          this.loading = true;
          if (!this.billingData.id) {
            const res = await this.$api['data/setMeal/combo']({ ...this.ruleForm });
            this.loading = false;
            if (res.code !== 200) return this.$message.error('增加套餐失败！');
            this.$message.success("增加套餐成功");
            this.modalShow = false;
            this.$emit("success");
          } else {
            const res = await this.$api['data/setMeal/modifyCombo']({ ...this.ruleForm });
            this.loading = false;
            if (res.code !== 200) return this.$message.error('修改套餐失败！');
            this.$message.success("修改套餐成功");
            this.modalShow = false;
            this.$emit("success");
          }
        }
      });
    },
    handlechange(selection, row) {
      let isExistence = false;
      this.selectTables.forEach((item, index) => {
        if (item.id === row.id) {
          isExistence = true;
          this.selectTables.splice(index, 1);
        }
      });
      if (!isExistence) {
        const json = JSON.parse(JSON.stringify(row));
        // this.$set(json, 'discount', false);
        this.$set(json, 'checkeds', true);
        this.selectTables.push(json);
      }
    },
    modalClose() {
      this.modalShow = false;
      this.ruleForm = {};
    },
    classificationSelection(val) {
      if (val && val.length > 0) {
        const nameList = [];
        let list = this.projectList;
        val.forEach(item => {
          list.forEach(json => {
            if (item === json.id) {
              nameList.push(json.dataName);
              if (json.children) list = json.children;
            }
          });
        });
        this.ruleForm.classifyName = nameList.join(">");
        this.ruleForm.allClassifyId = val.join(",");
        this.ruleForm.classifyId = val[val.length - 1];
      }
    },
    discountChange(item) {
      if (!item.discountRate) item.discountRate = 0;
      if (!item.discount) item.discount = 100;
      if (parseInt(item.discountRate) < parseInt(item.discount)) item.discountRate = item.discount;
      if (parseInt(item.discount) > 100) item.discount = 100;
      item.discountRate = parseInt(item.discountRate);
      const discountPrice = item.price * item.discountRate / 100;
      this.$set(item, 'discountPrice', Math.floor(discountPrice * 100) / 100);
    },
    allHandleChange(selection) {
      if (selection.length > 0) {
        selection.forEach(item => {
          let isExistence = false;
          this.selectTables.forEach(json => {
            if (json.id === item.id) {
              isExistence = true;
            }
          });
          if (!isExistence) {
            const json = JSON.parse(JSON.stringify(item));
            // this.$set(json, 'discount', false);
            this.$set(json, 'checkeds', true);
            this.selectTables.push(json);
          }
        });
      } else {
        this.tableData.forEach(item => {
          this.selectTables.forEach((json, index) => {
            if (json.id === item.id) {
              this.selectTables.splice(index, 1);
              index--;
            }
          });
        });
      }
    },
    valChange(val) {
      console.log(val);
      if (val) {
        if (!this.tableDataList || this.tableDataList.length === 0) return;
        this.tableData = [];
        this.tableDataList.forEach(item => {
          if (item.name.indexOf(val) > -1 || (item.searchCode && item.searchCode.indexOf(val) > -1)) this.tableData.push(item);
        });
      } else {
        this.tableData = JSON.parse(JSON.stringify(this.tableDataList));
      }
    },
  },
};
</script>

<style scoped lang='scss'>
.el-col-offset-8,.el-col-offset-2 {
  .el-button {
    margin-top: 15px;
    width: 100%;
    height: 40px;
  }
}
// /deep/.el-form-item__content{
//   margin-left: 50px !important;
// }
  .span{
    color: #ff6600;
  }
  .grey{
    color: #aaaaaa;
  }
  .bg{
    background: rgba(211,223,247,0.7);
    width: 50px;
    height: 25px;
    text-align: center;
    border-radius: 10px;
    color: #666;
    margin-top: 3px;
    line-height: 8px;
  }
  .product{
    display: flex;
  }
  .price{
    border-bottom: 1px solid #797979;
    padding-bottom: 10px;
    .el-col{
      display: flex;
    }
  }
  .el-row,span{
    line-height: 40px;
  }
  li{
    display: flex;
    margin-top: 5px;
  }
  .detailed{
    margin: 15px 0;
  }
  .font-weight{
    font-weight: bold;
  }
  div>span{
    margin-right: 25px;
  }
  .choose{
    max-height: 300px;
  }
  .demo-ruleForm{
    .spns{
      line-height: 40px;
      font-size: 18px;
      font-family: Source Han Sans CN;
      font-weight: 400;
      color: #F77464;
    }
  }
  .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
    margin-bottom: 18px;
  }
</style>
